Passed
Push — main ( d53ef8...c82fb0 )
by Andrii
01:47
created

utils.ts ➔ templateLine   B

Complexity

Conditions 6

Size

Total Lines 24
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 24
rs 8.4426
c 0
b 0
f 0
cc 6
1
import type {
2
  PathLike
3
} from "fs"
4
import {
5
  createReadStream,
6
  existsSync,
7
  mkdirSync,
8
  promises,
9
  writeFileSync
10
} from "fs"
11
import { dirname } from "path"
12
import { createInterface } from "readline"
13
14
const {
15
  appendFile: $appendFile
16
} = promises
17
, templateParser = /^(?<indentation>\s*)### <vars\s+(?<options>.*)\/>/
18
, kvParser = /(?<key>[^\s]+)=(?<value>[^\s]+)/g
19
20
export {
21
  templateLine,
22
  kvParser,
23
  createLineReader,
24
  appenderSync,
25
  arr2line,
26
  join
27
}
28
29
function createLineReader(path: PathLike) {
30
  return createInterface(createReadStream(path))
31
}
32
33
function appenderSync(path: string) {
34
  const dir = dirname(path)
35
36
  existsSync(dir) || mkdirSync(dir, {"recursive": true})
37
  writeFileSync(path, "")
38
39
  return (...lines: string[]) => $appendFile(path, lines.join(""))
40
}
41
42
function templateLine<O extends string>(line: string) {
43
  const templ = templateParser.exec(line)?.groups
44
45
  if (!templ) {
46
    if (line.includes('### <vars '))
47
      throw Error(`Fix RegExp! "${line}"`)
48
49
    return false
50
  }
51
52
  const {
53
    indentation,
54
    options
55
  } = templ
56
  , opts = {indentation} as {indentation: string} & Partial<Record<O, string>>
57
58
  let kv: undefined|{"key": keyof typeof opts, "value": string}
59
60
  while (kv = kvParser.exec(options)?.groups as typeof kv)
61
    //@ts-expect-error
62
    opts[kv.key as O] = kv.value
63
64
  return opts
65
}
66
67
function arr2line(indentation = "", ...source: (undefined|string)[]) {
68
  return `${
69
    indentation
70
  }${
71
    source.filter(x => x).join(" ")
72
  }\n`
73
}
74
75
76
function join(...lines: Array<Buffer|string|Array<Buffer|string>>) {
77
  return lines
78
  .flat()
79
  .join("\n")
80
}
81